<template>
  <div class="ai-room">
    <cp-nav-bar title="AI 聊天室">
      <template #right>
        <div class="nav-right">
          <van-icon
            name="setting-o"
            size="20"
            @click="togglePanel"
            :class="{ active: showPanel }"
          />
        </div>
      </template>
    </cp-nav-bar>
    <div class="ai-container">
      <!-- 聊天区 -->
      <div class="chat-wrapper" ref="msgListRef">
        <AIMessage v-for="msg in list" :key="msg.key" :item="msg" />
      </div>
      <!-- 参数区 -->
      <transition name="panel">
        <AIPanel
          v-show="showPanel"
          :form="form"
          @update="handleParamUpdate"
          @close="togglePanel"
        />
      </transition>
    </div>
    <!-- 遮罩层 -->
    <div v-show="showPanel" class="panel-overlay" @click="togglePanel"></div>
    <AIAction @send="handleSend" />
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick } from 'vue'
import { showToast } from 'vant'
import { guid } from '@/utils/guid'
import { aiChat } from '../../services/ai'
import type { AIChatParams, LocalChatMessage } from '../../services/ai'
import AIMessage from './components/AIMessage.vue'
import AIAction from './components/AIAction.vue'
import AIPanel from './components/AIPanel.vue'

interface ChatMsg extends LocalChatMessage {
  key: string
  type: 'text'
}

const list = ref<ChatMsg[]>([])
const msgListRef = ref<HTMLElement | null>(null)
const showPanel = ref(false)

// 参数
const form = ref<AIChatParams>({
  mode: 'hybrid',
  top_k: 10,
  max_token_for_text_unit: 4000,
  max_token_for_global_context: 4000,
  max_token_for_local_context: 4000,
  history_turns: 3,
  only_need_context: false,
  only_need_prompt: false,
  stream: false,
  query: ''
})

const togglePanel = () => {
  showPanel.value = !showPanel.value
  console.log('Panel toggled:', showPanel.value)
}

const handleParamUpdate = (params: Partial<AIChatParams>) => {
  Object.assign(form.value, params)
}

const scrollBottom = () => {
  nextTick(() => {
    if (msgListRef.value) {
      msgListRef.value.scrollTop = msgListRef.value.scrollHeight
    }
  })
}

const handleSend = async (text: string) => {
  if (!text) return
  // push self msg
  list.value.push({ key: guid(), role: 'ME', type: 'text', content: text })
  scrollBottom()
  // prepare payload
  form.value.query = text
  const payload: AIChatParams = {
    ...form.value,
    conversation_history: list.value
      .filter((m) => m.role === 'ME')
      .slice(-form.value.history_turns)
      .map((m) => ({
        role: m.role === 'ME' ? 'user' : 'assistant',
        content: m.content
      }))
  }
  try {
    const res: any = await aiChat(payload)
    const answer =
      typeof res === 'string' ? res : res.data || res.message || '无回复'
    list.value.push({ key: guid(), role: 'AI', type: 'text', content: answer })
    scrollBottom()
  } catch (e) {
    showToast('请求失败')
  }
}
</script>

<style lang="scss" scoped>
@use '@/styles/room.scss';
.ai-room {
  padding-top: 90px;
  min-height: 100vh;
  background: var(--cp-bg);
  display: flex;
  flex-direction: column;
  position: relative;

  .nav-right {
    .van-icon {
      color: var(--cp-text2);
      cursor: pointer;
      transition: color 0.3s ease;

      &:hover,
      &.active {
        color: var(--cp-primary);
      }
    }
  }

  .ai-container {
    flex: 1;
    display: flex;
    overflow: hidden;
    position: relative;

    .chat-wrapper {
      flex: 1;
      overflow-y: auto;
      padding-bottom: 120px;
      transition: margin-right 0.3s ease;
    }
  }

  .panel-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.3);
    z-index: 1000;
  }
}

// 面板动画
.panel-enter-active,
.panel-leave-active {
  transition: transform 0.3s ease;
}

.panel-enter-from,
.panel-leave-to {
  transform: translateX(100%);
}

.panel-enter-to,
.panel-leave-from {
  transform: translateX(0);
}
</style>
